package com.cloudpark.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloudpark.service.ParkRecordService;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.cloudpark.common.util.Constants;
import com.cloudpark.common.util.JsonUtil;
import com.cloudpark.common.util.MessageUtil;
import com.cloudpark.common.util.ObjectUtil;
import com.cloudpark.common.util.Pagination;
import com.cloudpark.model.entity.AdminUser;
import com.cloudpark.model.entity.Park;
import com.cloudpark.service.EstateService;
import com.cloudpark.service.ParkService;
import com.google.common.collect.Maps;

@Controller
@RequestMapping("/vehicle")
public class VehicleController extends BaseController {

    private static final Logger log = Logger.getLogger(VehicleController.class);
    
    @Autowired
    private ParkService parkService;
    @Autowired
    private ParkRecordService parkRecordService;
    @Autowired
    private EstateService estateService;

    @RequestMapping(value = "/parkList", method = RequestMethod.GET)
    public ModelAndView parkList(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/parkList.jsp");
        initMenu(request, response);
        return mv;
    }
    
    @RequestMapping(value = "/queryParkList", method = RequestMethod.POST)
    @ResponseBody
    public String queryParkList(HttpServletRequest request,
            @RequestParam(value = "start", defaultValue = "0") int start,
            @RequestParam(value = "length", defaultValue = "10") int length, @RequestParam(value = "draw") int draw,
            HttpServletResponse response) {
        String result = "";
        try {
            AdminUser adminUser = isSessionExpire(request, response);
            String city = request.getParameter("city");
            String area = request.getParameter("area");
            String parkName = request.getParameter("parkName");
            Map<String, String> params = new HashMap<String, String>();
            if (ObjectUtil.isNotBlank(city)) {
                params.put("city", city);
            }
            if (ObjectUtil.isNotBlank(area)) {
                params.put("area", area);
            }
            if (ObjectUtil.isNotBlank(parkName)) {
            	params.put("parkName", parkName);
            }
            Pagination page = parkService.queryParkList(params, start, length, adminUser.getEstateId());
            result = JsonUtil.toJSONDataTables(page, draw);
        } catch (Exception e) {
            log.error("query park list error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }
    
    @RequestMapping(value = "/editPark", method = RequestMethod.GET)
    public ModelAndView editPark(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/editPark.jsp");
        initMenu(request, response);
        String estateOptions = estateService.queryEstateOptions();
        request.setAttribute("estateOptions", estateOptions);
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            Park park = parkService.queryParkById(Long.valueOf(id));
            mv.addObject("park", park);
            mv.addObject("isUpdate", 1);
        } else {
            mv.addObject("isUpdate", 0);
        }
        return mv;
    }
    
    @RequestMapping(value = "/queryParkOptions", method = RequestMethod.POST)
    @ResponseBody
    public String queryParkOptions(HttpServletRequest request,
            HttpServletResponse response) {
    	String result = "";
    	Map<String, Object> map = Maps.newHashMap();
        try {
        	AdminUser adminUser = isSessionExpire(request, response);
        	String options = parkService.queryParkOptions(adminUser.getEstateId());
        	map.put("code", Constants.OK);
        	map.put("options", options);
        	result = JSON.toJSONString(map);
        } catch (Exception e) {
            log.error("query park options error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }
    
    @RequestMapping(value = "/saveOrUpdatePark", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView saveOrUpdatePark(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/editPark.jsp");
        initMenu(request, response);
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String estateId = request.getParameter("estateId");
        String type = request.getParameter("type");
        String freeTime = request.getParameter("freeTime");
        String allowStayTime = request.getParameter("allowStayTime");
        String totalParkNum = request.getParameter("totalParkNum");
        String remainParkNum = request.getParameter("remainParkNum");
        String price = request.getParameter("price");
        String city = request.getParameter("city");
        String area = request.getParameter("area");
        String street = request.getParameter("street");
        String chargeDes = request.getParameter("chargeDes");

        try {
            Park park = null;
            if (ObjectUtil.isNotBlank(id)) {
            	park = parkService.queryParkById(Long.valueOf(id));
                mv.addObject("isUpdate", 1);
            } else {
            	park = new Park();
                mv.addObject("isUpdate", 0);
                park.setCreatedTime(new Date());
            }
            park.setName(name);
            park.setEstateId(Long.valueOf(estateId));
            park.setType(Integer.valueOf(type));
            park.setFreeTime(Integer.valueOf(freeTime));
            park.setAllowStayTime(Integer.valueOf(allowStayTime));
            park.setTotalParkNum(Integer.valueOf(totalParkNum));
            park.setRemainParkNum(Integer.valueOf(remainParkNum));
            park.setPrice(Double.valueOf(price));
            park.setCity(city);
            park.setArea(area);
            park.setStreet(street);
            park.setChargeDes(chargeDes);

            parkService.saveOrUpdatePark(park);
            String estateOptions = estateService.queryEstateOptions();
            request.setAttribute("estateOptions", estateOptions);
            mv.addObject("park", park);
            mv.addObject("message", "编辑停车场信息成功!");
            mv.addObject("saveOk", "1");
        } catch (Exception e) {
            log.error("编辑停车场信息失败", e);
            mv.addObject("message", "编辑停车场信息失败!");
            mv.addObject("saveOk", "2");
        }
        return mv;
    }
    
    @RequestMapping(value = "/deletePark", method = RequestMethod.POST)
	@ResponseBody
	public String deletePark(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		Map<String, Object> map = new HashMap<String, Object>();
		String idStr = request.getParameter("id");
		try {
			Long id = Long.parseLong(idStr);
			parkService.deleteParkById(id);
			result = JsonUtil.success("删除成功");
		} catch (Exception e) {
			log.error("delete park error :", e);
			result = JsonUtil.success("服务器忙!");
		}
		return result;
	}

    @RequestMapping(value = "/online", method = RequestMethod.GET)
    public ModelAndView online(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/online.jsp");
        initMenu(request, response);
        return mv;
    }

    @RequestMapping(value = "/parkLot", method = RequestMethod.GET)
    public ModelAndView parkLot(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/parkLot.jsp");
        initMenu(request, response);
        return mv;
    }

    @RequestMapping(value = "/monthVehicle", method = RequestMethod.GET)
    public ModelAndView monthVehicle(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/monthVehicle.jsp");
        initMenu(request, response);
        return mv;
    }

    @RequestMapping(value = "/freeVehicle", method = RequestMethod.GET)
    public ModelAndView freeVehicle(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/freeVehicle.jsp");
        initMenu(request, response);
        return mv;
    }

    @RequestMapping(value = "/blacklist", method = RequestMethod.GET)
    public ModelAndView blacklist(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/blacklist.jsp");
        initMenu(request, response);
        return mv;
    }

    @RequestMapping(value = "/device", method = RequestMethod.GET)
    public ModelAndView device(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("vehicle/device.jsp");
        initMenu(request, response);
        return mv;
    }
}
